#include "qtlogger.h"

#include <QDir>

QtLogger::QtLogger()
{
    stopped = false;
    QDir dir;
    logFileDir = dir.currentPath () + "/log/";
    QDateTime DT = QDateTime::currentDateTime();
    QString DTStr = QString("%1").arg(DT.toString("yyyy-MM-dd"));
    logFileName = DTStr + ".log";

    if(!dir.exists(logFileDir))
    {
        dir.mkpath(logFileDir);
    }
    logFilePath = logFileDir + logFileName;
    logFile =  new QFile(logFilePath);
    logFile->open(QIODevice::WriteOnly | QIODevice::Append);
}

void QtLogger::WriteLog(QString logMsg)
{
    mutex.lock();
    logQueue.push_back(logMsg);
    mutex.unlock();
}

void QtLogger::run()
{
    while (!stopped) {
        mutex.lock();
        if(!logQueue.isEmpty())
        {
            QString logMsg = logQueue.front();
            logQueue.pop_front();
            mutex.unlock();
            QTextStream logStream(logFile);
            logStream<<(logMsg)<<endl;
            logFile->flush();
        }
        else
        {
            mutex.unlock();
        }

    }
}

void QtLogger::stop()
{
    stopped = true;
}

QtLogger::~QtLogger()
{
    logFile->flush();
    logFile->close();
}
